package cn.modfun.common.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class JDBCUtil {

    private String type;

    private String ip;

    private String port = "3306";

    private String database;

    private String user;

    private String password;

    private String charset = "utf8";

    private Map<String,String> driverMap = new HashMap<String,String>();

    private Map<String,String> jdbcUrlMap = new HashMap<String,String>();

    private Map<String,Integer> portMap = new HashMap<String,Integer>();

    public JDBCUtil(String type,String ip,String port,String database,String user,String password,String charset){
        initMapping();
        this.type = type;
        this.ip = ip;
        this.port = port!=null?port:this.port;
        this.database = database;
        this.user = user;
        this.password = password;
        this.charset = charset!=null?charset:this.charset;
    }

    private void initMapping(){
        driverMap.put("sqlite","org.sqlite.JDBC");
        driverMap.put("mysql","com.mysql.jdbc.Driver");

        jdbcUrlMap.put("sqlite","jdbc:sqlite:${source_ip}");
        jdbcUrlMap.put("mysql","jdbc:mysql://${source_ip}${source_port}${database}?characterEncoding=${characterEncoding}&zeroDateTimeBehavior=convertToNull");

        portMap.put("mysql",3306);
    }

    public Connection getConnection(){
        Connection conn = null;
        String driver = driverMap.get(type);
        String jdbcUrl = jdbcUrlMap.get(type);
        /**/
        jdbcUrl = jdbcUrl.replace("${source_ip}",ip);
        jdbcUrl = jdbcUrl.replace("${source_port}",":"+port);
        jdbcUrl = jdbcUrl.replace("${database}",database!=null?("/"+database):"");
        jdbcUrl = jdbcUrl.replace("${characterEncoding}",charset);
        /**/
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(jdbcUrl, user,password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
}
